import shutil
from Crypto.Hash import SHA
from Crypto.Cipher import ARC4
from struct import unpack
from tempfile import NamedTemporaryFile
from pathlib import Path


def decryptSQLite(in_file, out_file, password):

    ret = None

    with open(in_file, 'rb') as f:
        key = SHA.new(password).digest()[:16]  # win crypto api seems to use 16b
        header = ARC4.new(key).decrypt(f.read(1024))  # preemptively read header
        if header[0:15] == b'SQLite format 3':  # sanity check, proceed if valid
            declared_ps = unpack('>H', header[16:18])[0]  # ushort_be @ 16
            if declared_ps == 1:
                declared_ps = 65536
            t = NamedTemporaryFile(delete=False, suffix='.sqlite')
            f.seek(0)

            while True:
                block = f.read(declared_ps)
                if not block:
                    break
                t.write(ARC4.new(key).decrypt(block))  # reinitialize rc4
            t.close()
            ret = t.name
    if ret:
        shutil.move(ret, out_file)
    return ret


if __name__ == '__main__':
    src_path = 'AppConfig.db_files'
    password = b'MobileForensic@2013@'

    des_path = Path(src_path).parent / f"{Path(src_path).stem}_bak{Path(src_path).suffix}"


    decryptSQLite(src_path, des_path, password)

